/* eslint-disable react/jsx-key */
import React, { useState, useRef, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { Card, Switch, Button, Modal, message, Popconfirm, Tooltip } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { company, companydetail } from '@/services/business';
import CompanyDetail from '@/components/CompanyDetail';
import { user } from '@/services/basic';
import CompanyName from '@/components/CompanyName';


let shFields = {
    actual_reason: {
      value: null,
      type: 'textarea',
      title: '实际情况（开票情况，财务处理情况，平时沟通情况）',
      name: ['actual_reason'],
      required: false,
      col: { span: 24 },
    },
  },
  status = {
    account_pending: '会计主管录入中',
    chief_pending: '会计总监审核中',
    cancel: '总监驳回',
    completed: '已完成',
  };

function Monthchange(props) {
  let defaultFields = {
    company_id: {
      value: null,
      type: 'select',
      title: '代账公司',
      name: ['company_id'],
      required: true,
      options: {
        database: company,
        params: {
          is_all: 1,
          type: -1,
          account_user_id: props.user.currentUser.id,
          status: 'completed',
          service_type: 'account',
        },
      },
      col: { span: 24 },
    },
    unit_price: {
      value: null,
      type: 'inputnumber',
      title: '变更后月收费',
      name: ['unit_price'],
      required: true,
      col: { span: 24 },
    },
    account_user_id: {
      value: null,
      type: 'select',
      title: '审核人',
      name: ['account_user_id'],
      required: true,
      options: {
        database: user,
        params: { is_all: 1, role_type: 4 },
      },
      col: { span: 24 },
    },
    reason: {
      value: null,
      type: 'textarea',
      title: '变更原因',
      name: ['reason'],
      required: false,
      col: { span: 24 },
    },
  };
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    [unitprice, cp] = useState(0);

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = useMemo(() => {
    return [
      {
        title: '公司名称',
        width: 260,
        dataIndex: 'company_name',
        key: 'company_name',
        render: (_, row) => (
          <CompanyName
            row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
            reload={reload}
          />
        ),
      },
      {
        title: '变更前月收费',
        dataIndex: 'origin_unit_price',
        key: 'origin_unit_price',
      },
      {
        title: '变更后月收费',
        dataIndex: 'unit_price',
        key: 'unit_price',
      },
      {
        title: '变更原因',
        dataIndex: 'reason',
        key: 'reason',
      },
      {
        title: '发起人',
        dataIndex: 'creator_name',
        key: 'creator_name',
      },
      {
        title: '审核人',
        dataIndex: 'account_user_name',
        key: 'account_user_name',
      },
      {
        title: '实际情况',
        dataIndex: 'actual_reason',
        key: 'actual_reason',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (_, row) => <span>{status[row.status]}</span>,
      },

      {
        title: '操作',
        valueType: 'option',
        width: 140,
        render: (text, record, _, action) => [
          <a
            disabled={record.status != 'account_pending'}
            style={{ color: record.status != 'account_pending' ? '#999' : '#1890ff' }}
            onClick={() => {
              if (record.status != 'account_pending') {
                return;
              }
              cvs(true);
              cf(() => {
                for (let i in shFields) {
                  shFields[i].value = record[i];
                }
                return { ...shFields };
              });
              ciftype({
                val: 'audit',
                title: '实际情况',
                id: record.id,
              });
            }}
          >
            实际情况
          </a>,
        ],
      },
    ];
  }, []);

  let extrarender = [
    <div
      className="action"
      title="发起月收费变更"
      onClick={() => {
        cvs(true);
        cf((fields) => {
          for (let i in fields) {
            fields[i].value = null;
          }
          return { ...fields };
        });
        ciftype({
          val: 'add',
          title: '发起月收费变更',
        });
      }}
    >
      <PlusOutlined />
    </div>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'customer/month_charge',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'audit') {
      dispatch({
        type: 'customer/account_repair',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 发起解约or批量删除
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/month_charge"
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={iftype.val == 'detail' ? 1200 : 600}
        destroyOnClose={true}
      >
        {iftype.val == 'detail' ? (
          <CompanyDetail id={iftype.id || ''} />
        ) : (
          <div>
            {iftype.val == 'add' && (
              <p style={{ marginBottom: 0 }}>当前选择公司的月收费：{unitprice}</p>
            )}
            <InitForm
              fields={fields}
              submitData={(values) => {
                saveData(values);
              }}
              onChange={(changedValues, allValues) => {
                //联动操作
                let label = Object.keys(changedValues)[0],
                  value = Object.values(changedValues)[0];
                if (label == 'company_id') {
                  companydetail({ id: value }).then((res) => {
                    cp(res?.data?.unit_price ?? 0);
                  });
                }
              }}
              submitting={
                props.loading.effects['customer/month_charge'] ||
                props.loading.effects['customer/editrescind'] ||
                !vs
              }
            />
          </div>
        )}
      </Modal>
    </div>
  );
}

export default connect(({ customer, loading, user }) => ({
  customer,
  loading,
  user,
}))(Monthchange);
